package com.easy.dfcapi.service.impl;

import com.easy.common.bean.Result;
import com.easy.common.config.Global;
import com.easy.common.constant.EnumConfig;
import com.easy.common.util.Utility;
import com.easy.common.utils.SpringContextHolder;
import com.easy.common.utils.StringUtil;
import com.easy.dfcapi.entity.*;
import com.easy.dfcapi.mapper.*;
import com.easy.dfcapi.res.*;
import com.easy.dfcapi.service.ApiStoreService;
import com.easy.dfcapi.utils.ApiSessionUser;
import com.easy.dfcapi.utils.ServletHelper;
import com.easy.dfcapi.utils.Util;
import com.easy.modules.sys.entity.Para;
import com.easy.modules.sys.mapper.ParaMapper;
import io.rong.RongCloud;
import io.rong.models.TokenResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by VULCANTSeries on 2017/5/10.
 */
@Service
@Transactional(readOnly = true)
public class ApiStoreServiceImpl implements ApiStoreService {

    @Autowired
    private ApiUserMapper userMapper;

    @Autowired
    private ApiStoreMapper storeMapper;

    @Autowired
    private ParaMapper paraMapper;

    @Autowired
    private ApiAdvertMapper advertMapper;

    @Autowired
    private ApiFollowMapper followMapper;


    @Autowired
    private ApiStoreUpgradeMapper storeUpgradeMapper;

    @Override
    @Transactional(readOnly = false)
    public Result StoreAdd(Response<StoreRes> response) throws Exception {
        Result rt = new Result();
        try {
            StoreRes data = response.getData(StoreRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            Integer isAudit = 0;
            Para para  = paraMapper.getByParaName("storeAudit");
            if(para != null){
                isAudit = StringUtil.toInt(para.getParaValue());
            }
            Date now = new Date();
            ApiStore store = new ApiStore();
            store.setStoreName(data.getStoreName());
            store.setStoreImg(data.getStoreImg());
            store.setStoreAvatar(data.getStoreAvatar());
            store.setEmail(data.getEmail());
            store.setPhone(data.getPhone());
            store.setAddress(data.getAddress());
            store.setScope(data.getScope());
            store.setLicenseNo(data.getLicenseNo());
            store.setLicenseImg(data.getLicenseImg());
            store.setLegalName(data.getLegalName());
            store.setLegalIdimg(data.getLegalIdimg());
            store.setLegalIdno(data.getLegalIdno());
            store.setLegalMobile(data.getLegalMobile());
            store.setLegalArea(data.getLegalArea());
            store.setAgentName(data.getAgentName());
            store.setAgentIdno(data.getAgentIdno());
            store.setAgentMobile(data.getAgentMobile());
            store.setUser(user);
            store.setStoreType(sessionUser.getStoreType());
            store.setStoreStar(1);
            store.setIsRealName(0);
            store.setIsAudit(isAudit);
            store.preInsert(now);
            if(storeMapper.insert(store)>0){
                rt.setStatus(EnumConfig.S_CODE.OK);

                Integer storeCount = storeMapper.getCountByUserType(user.getUserId(), sessionUser.getStoreType());
                sessionUser.setUserId(user.getUserId());
                sessionUser.setStoreId(store.getStoreId());
                sessionUser.setUserName(user.getUserName());
                String token = ServletHelper.getTokenByUser(sessionUser);
                Map map = new HashMap();
                map.put("token", token);

                //聊天用户获取开始
                RongCloud roungcloud = RongCloud.getInstance();
                TokenResult tokenResult = roungcloud.user.getToken(user.getId(),user.getUserName(), SpringContextHolder.getStatic()+"/"+user.getAvatar());
                if(tokenResult.getCode()==200){
                    map.put("imUserToken", tokenResult.getToken());
                }
                else {
                    map.put("imUserToken", "");
                }
                //聊天用户获取结束

                map.put("isRealName", user.getIsRealName());
                map.put("userName", user.getUserName());
                map.put("userNick", user.getUserNick());
                map.put("avatar", user.getAvatar());
                map.put("avatarUrl", user.getAvatarUrl());
                map.put("storeId", store.getId());
                map.put("storeCount", storeCount);
                rt.setData(map);
            }
            else {
                rt.setStatus(EnumConfig.S_CODE.FAIL);
            }


        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }

    @Override
    public Result StoreInfo(Response<UserRes> response)  throws Exception{
        Result rt = new Result();
        try {
            UserRes data = response.getData(UserRes.class);
            String avatar = data.getAvatar();
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiStore store = null;
            if(Utility.isNullorEmpty(data.getStoreId())) {
                store = storeMapper.getByStoreId(sessionUser.getStoreId());
                if (store == null) {
                    rt.setStatus(EnumConfig.S_CODE.STORE_NOT_EXIST);
                    return rt;
                }
            }
            else {
                store = storeMapper.get(data.getStoreId());
                if (store == null) {
                    rt.setStatus(EnumConfig.S_CODE.STORE_NOT_EXIST);
                    return rt;
                }
            }
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("storeId",store.getId());
            map.put("storeName",store.getStoreName());
            map.put("storeLevel",store.getStoreLevel());
            map.put("storeStar",store.getStoreStar());
            map.put("storeType",store.getStoreType());
            map.put("storeAvatar",store.getStoreAvatar());
            map.put("storeAvatarUrl",store.getStoreAvatarUrl());
            map.put("storeImg",store.getStoreImg());
            map.put("storeImgUrl",store.getStoreImgUrl());
            map.put("isRealName",store.getIsRealName());
            map.put("isAudit",store.getIsAudit());

            if(store.getStoreType()==1) {
                map.put("storeLevelName", "原料商");
            }
            else if(store.getStoreType()==2) {
                if (store.getStoreLevel() == 1) map.put("storeLevelName", "童品汇");
                else if (store.getStoreLevel() == 2) map.put("storeLevelName", "潮牌馆");
                else if (store.getStoreLevel() == 3) map.put("storeLevelName", "品牌馆");
                else if (store.getStoreLevel() == 4) map.put("storeLevelName", "尾品汇");
                else map.put("storeLevelName", "未知");
            }
            else if(store.getStoreType()==3) {
                map.put("storeLevelName", "批发商");
            }
            else if(store.getStoreType()==4) {
                map.put("storeLevelName", "经销商");
            }

            rt.setData(map);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }
    @Override
    public Result StoreDetail(Response<UserRes> response) throws Exception {
        Result rt = new Result();
        try {
            UserRes data = response.getData(UserRes.class);
            String avatar = data.getAvatar();
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiStore store = null;
            if(Utility.isNullorEmpty(data.getStoreId())) {
                store = storeMapper.getByStoreId(sessionUser.getStoreId());
                if (store == null) {
                    rt.setStatus(EnumConfig.S_CODE.STORE_NOT_EXIST);
                    return rt;
                }
            }
            else {
                store = storeMapper.get(data.getStoreId());
                if (store == null) {
                    rt.setStatus(EnumConfig.S_CODE.STORE_NOT_EXIST);
                    return rt;
                }
            }

            rt.setData(store);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }

    @Override
    public Result StoreList(Response<UserRes> response) throws Exception {
        Result rt = new Result();
        try {
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }

            List<ApiStore> storeList = storeMapper.getListByUserType(sessionUser.getUserId(), sessionUser.getUserType());
            if(storeList==null ){
                rt.setStatus(EnumConfig.S_CODE.STORE_NOT_EXIST);
                return rt;
            }
            List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
            for(int i = 0;i < storeList.size(); i++){
                ApiStore store = storeList.get(i);
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("storeId",store.getId());
                map.put("storeName",store.getStoreName());
                map.put("storeLevel",store.getStoreLevel());
                map.put("storeStar",store.getStoreStar());
                map.put("storeType",store.getStoreType());
                map.put("storeAvatar",store.getStoreAvatar());
                map.put("storeAvatarUrl",store.getStoreAvatarUrl());
                map.put("storeImg",store.getStoreImg());
                map.put("storeImgUrl",store.getStoreImgUrl());
                map.put("isRealName",store.getIsRealName());
                map.put("isAudit",store.getIsAudit());
                if(store.getStoreType()==1) {
                    map.put("storeLevelName", "原料商");
                }
                else if(store.getStoreType()==2) {
                    if (store.getStoreLevel() == 1) map.put("storeLevelName", "童品汇");
                    else if (store.getStoreLevel() == 2) map.put("storeLevelName", "潮牌馆");
                    else if (store.getStoreLevel() == 3) map.put("storeLevelName", "品牌馆");
                    else if (store.getStoreLevel() == 4) map.put("storeLevelName", "尾品汇");
                    else map.put("storeLevelName", "未知");
                }
                else if(store.getStoreType()==3) {
                    map.put("storeLevelName", "批发商");
                }
                else if(store.getStoreType()==4) {
                    map.put("storeLevelName", "经销商");
                }

                list.add(map);
            }
            rt.setData(list);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result StoreAvatar(List<ImgReq> imgList, Response<StoreRes> response) throws Exception {
        Result rt = new Result();
        try {
            StoreRes data = response.getData(StoreRes.class);
            Integer storeAvatar = data.getStoreAvatar();
            if(imgList.size()>0){
                storeAvatar = imgList.get(0).getImgId();
            }

            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiStore store = storeMapper.getByStoreId(sessionUser.getStoreId());
            if(store == null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            storeMapper.updateAvatarByStoreId(store.getStoreId(),storeAvatar);
            rt.setData(imgList);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result StoreImg(List<ImgReq> imgList, Response<StoreRes> response) throws Exception {
        Result rt = new Result();
        try {
            StoreRes data = response.getData(StoreRes.class);
            Integer storeImg = data.getStoreImg();
            if(imgList.size()>0){
                storeImg = imgList.get(0).getImgId();
            }
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiStore store = storeMapper.getByStoreId(sessionUser.getStoreId());
            if(store == null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            storeMapper.updateImgByStoreId(store.getStoreId(),storeImg);

            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(imgList);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result Upgrade(Response<StoreRes> response) throws Exception{
        Result rt = new Result();
        try {
            StoreRes data = response.getData(StoreRes.class);
            Integer storeAvatar = data.getStoreAvatar();
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiStore store = storeMapper.getByStoreId(sessionUser.getStoreId());
            if(store == null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }

            if(store.getStoreLevel() == data.getStoreLevel()){
                rt.setStatus(EnumConfig.S_CODE.STORE_LEVEL_IS_SAME);
                return rt;
            }
            if(store.getStoreLevel() > data.getStoreLevel()){
                rt.setStatus(EnumConfig.S_CODE.STORE_LEVEL_NOT_DOWN);
                return rt;
            }

            ApiStoreUpgrade upgrade = storeUpgradeMapper.findByStoreUpgradeId(store.getStoreId(),data.getStoreLevel());
            if(upgrade == null) {
                upgrade = new ApiStoreUpgrade();
                Date now = new Date();

                upgrade.setStoreId(store.getStoreId());
                upgrade.setStoreLevel(data.getStoreLevel());
                upgrade.setUpgradeLevel(data.getUpgradeLevel());
                upgrade.setAptitude(data.getAptitude());

                upgrade.setCreateTime(now);
                upgrade.setAuditStatus("0");
                upgrade.setEndStatus("0");
                upgrade.setStartDate(now);
                BigDecimal amnt = new BigDecimal(0);

                if(store.getStoreLevel()==1 && upgrade.getUpgradeLevel()==2){
                    amnt = storeUpgradeMapper.getUpgradeAmnt(1);
                }
                else if(store.getStoreLevel()==1 && upgrade.getUpgradeLevel()==3) {
                    amnt = storeUpgradeMapper.getUpgradeAmnt(2);
                }
                else if(store.getStoreLevel()==2 && upgrade.getUpgradeLevel()==3) {
                    amnt = storeUpgradeMapper.getUpgradeAmnt(3);
                }
                upgrade.setAmnt(amnt);
                storeUpgradeMapper.addUpgrade(upgrade);
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("auditStatus",upgrade.getAuditStatus());
                map.put("message","申请完成，待审核");
                map.put("payAmnt",upgrade.getAmnt());
                //map.put("auditAmnt",upgrade.getAmnt());
                rt.setData(map);
                rt.setStatus(EnumConfig.S_CODE.OK);
            }
            else {
                if(upgrade.getAuditStatus().equals("0")){//申请中
                    Map<String,Object> map = new HashMap<String,Object>();
                    map.put("auditStatus",upgrade.getAuditStatus());
                    map.put("message","申请中，待审核");
                    map.put("payAmnt",upgrade.getAmnt());
                    rt.setData(map);
                    rt.setStatus(EnumConfig.S_CODE.OK);
                }
                else if(upgrade.getAuditStatus().equals("1")){
                    if(upgrade.getEndStatus().equals("0")){
                        Map<String,Object> map = new HashMap<String,Object>();
                        map.put("auditStatus",upgrade.getAuditStatus());
                        map.put("message","审核通过，待支付");
                        map.put("payId",upgrade.getId());
                        map.put("payName","upgradePay");
                        map.put("payAmnt",upgrade.getAmnt());
                        map.put("payStoreId",store.getStoreId());
                        if(upgrade.getUpgradeLevel()==2) {
                            map.put("payProductName","升级为潮流馆");
                            map.put("payProductDesc","店铺由童品汇升级为潮流馆");
                        }
                        else if(upgrade.getUpgradeLevel()==3) {
                            if(store.getStoreLevel()==1){
                                map.put("payProductName","升级为品牌馆");
                                map.put("payProductDesc","店铺由童品汇升级为潮流馆");
                            }
                            else {
                                map.put("payProductName","升级为品牌馆");
                                map.put("payProductDesc","店铺由潮流馆升级为品牌馆");
                            }
                        }
                        map.put("payMode","aliPay,weChatPay");
                        rt.setData(map);
                        rt.setStatus(EnumConfig.S_CODE.OK);
                    }
                    else {
                        Map<String,Object> map = new HashMap<String,Object>();
                        map.put("auditStatus",upgrade.getAuditStatus());
                        map.put("message","支付完成");
                        map.put("amnt",upgrade.getAmnt());//支付金额
                        rt.setData(map);
                        rt.setStatus(EnumConfig.S_CODE.OK);
                    }

                }
                else {
                    Map<String,Object> map = new HashMap<String,Object>();
                    map.put("auditStatus",upgrade.getAuditStatus());
                    map.put("message","已失效");
                    map.put("amnt",upgrade.getAmnt());//支付金额
                    rt.setData(map);
                    rt.setStatus(EnumConfig.S_CODE.OK);
                }
            }
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result UpgradePay(Response<PayInfoRes> response)  throws Exception{
        Result rt = new Result();
        try {
            PayInfoRes data = response.getData(PayInfoRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiStore store = storeMapper.getByStoreId(sessionUser.getStoreId());
            if(store == null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            Map<String,Object> map = new HashMap<String,Object>();

            Date now = new Date();
            PayProductInfo info = new PayProductInfo();
            info.setTradeNo(Util.getOrderItemNo());
            info.setTotalAmnt(data.getPayAmnt());
            info.setProductName(data.getPayProductName());
            info.setProductDesc(data.getPayProductDesc());
            info.setCreateTime(now);
            info.setExpireTime(new Date(now.getTime()+900000));
            //info.setNotifyUrl(url+"${apiPath}/store/aliNotify");
            info.setNotifyUrl(SpringContextHolder.getContextPath()+Global.getApiPath()+"/2.0/store/AliNotify");

            if(data.getPayMode().equals("aliPay")){
                AliPayInfo aliPay = new AliPayInfo();
                String zBody = aliPay.getAliPayInfo(info);
                map.put("payId",data.getPayId());
                map.put("tradeNo",info.getTradeNo());
                map.put("payName","aliPay");
                map.put("payInfo",zBody);
                storeUpgradeMapper.updateTradeNo(data.getPayId(),info.getTradeNo());

            }
            if(data.getPayMode().equals("weChatPay")){
                AliPayInfo aliPay = new AliPayInfo();
                WeChatPayInfo weChatPay = new WeChatPayInfo();
                map.put("payId",data.getPayId());
                map.put("tradeNo",info.getTradeNo());
                map.put("payName","weChatPay");
                map.put("payInfo",weChatPay.getWeChatPayInfo(info));
            }
            rt.setData(map);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }

    @Override
    public Result UpgradeQuery(Response<StoreRes> response)  throws Exception{
        Result rt = new Result();
        try {
            StoreRes data = response.getData(StoreRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiStore store = storeMapper.getByStoreId(sessionUser.getStoreId());
            if(store == null){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;
            }
            ApiStoreUpgrade upgrade = storeUpgradeMapper.findByStoreId(store.getStoreId());
            if(upgrade == null) {
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("auditStatus",-1);
                map.put("storeId",store.getId());
                map.put("storeName",store.getStoreName());
                map.put("storeAvatar",store.getStoreAvatar());
                map.put("storeAvatarUrl",store.getStoreAvatarUrl());
                map.put("storeImg",store.getStoreImg());
                map.put("storeImgUrl",store.getStoreImgUrl());

                map.put("storeLevel",store.getStoreLevel());

                if(store.getStoreType()==1) {
                    map.put("storeLevelName", "原料商");
                }
                else if(store.getStoreType()==2) {
                    if (store.getStoreLevel() == 1) map.put("storeLevelName", "童品汇");
                    else if (store.getStoreLevel() == 2) map.put("storeLevelName", "潮牌馆");
                    else if (store.getStoreLevel() == 3) map.put("storeLevelName", "品牌馆");
                    else if (store.getStoreLevel() == 4) map.put("storeLevelName", "尾品汇");
                    else map.put("storeLevelName", "未知");
                }
                else if(store.getStoreType()==3) {
                    map.put("storeLevelName", "批发商");
                }
                else if(store.getStoreType()==4) {
                    map.put("storeLevelName", "经销商");
                }
                rt.setData(map);
                rt.setStatus(EnumConfig.S_CODE.OK);
            }
            else {
                if(upgrade.getAuditStatus().equals("0")){//申请中
                    Map<String,Object> map = new HashMap<String,Object>();
                    map.put("auditStatus",upgrade.getAuditStatus());
                    map.put("storeId",store.getStoreId());
                    map.put("storeName",store.getStoreName());
                    map.put("storeAvatar",store.getStoreAvatar());
                    map.put("storeAvatarUrl",store.getStoreAvatarUrl());
                    map.put("storeImg",store.getStoreImg());
                    map.put("storeImgUrl",store.getStoreImgUrl());

                    map.put("storeLevel",store.getStoreLevel());
                    if(store.getStoreType()==1) {
                        map.put("storeLevelName", "原料商");
                    }
                    else if(store.getStoreType()==2) {
                        if (store.getStoreLevel() == 1) map.put("storeLevelName", "童品汇");
                        else if (store.getStoreLevel() == 2) map.put("storeLevelName", "潮牌馆");
                        else if (store.getStoreLevel() == 3) map.put("storeLevelName", "品牌馆");
                        else if (store.getStoreLevel() == 4) map.put("storeLevelName", "尾品汇");
                        else map.put("storeLevelName", "未知");
                    }
                    else if(store.getStoreType()==3) {
                        map.put("storeLevelName", "批发商");
                    }
                    else if(store.getStoreType()==4) {
                        map.put("storeLevelName", "经销商");
                    }
                    map.put("upgradeLevel",upgrade.getUpgradeLevel());
                    map.put("message","申请中，待审核");
                    map.put("payAmnt",upgrade.getAmnt());
                    rt.setData(map);
                    rt.setStatus(EnumConfig.S_CODE.OK);
                }
                else if(upgrade.getAuditStatus().equals("1")){
                    if(upgrade.getEndStatus().equals("0")){
                        Map<String,Object> map = new HashMap<String,Object>();
                        map.put("auditStatus",upgrade.getAuditStatus());
                        map.put("storeId",store.getStoreId());
                        map.put("storeName",store.getStoreName());
                        map.put("storeAvatar",store.getStoreAvatar());
                        map.put("storeAvatarUrl",store.getStoreAvatarUrl());
                        map.put("storeImg",store.getStoreImg());
                        map.put("storeImgUrl",store.getStoreImgUrl());

                        map.put("storeLevel",store.getStoreLevel());
                        if(store.getStoreType()==1) {
                            map.put("storeLevelName", "原料商");
                        }
                        else if(store.getStoreType()==2) {
                            if (store.getStoreLevel() == 1) map.put("storeLevelName", "童品汇");
                            else if (store.getStoreLevel() == 2) map.put("storeLevelName", "潮牌馆");
                            else if (store.getStoreLevel() == 3) map.put("storeLevelName", "品牌馆");
                            else if (store.getStoreLevel() == 4) map.put("storeLevelName", "尾品汇");
                            else map.put("storeLevelName", "未知");
                        }
                        else if(store.getStoreType()==3) {
                            map.put("storeLevelName", "批发商");
                        }
                        else if(store.getStoreType()==4) {
                            map.put("storeLevelName", "经销商");
                        }
                        map.put("message","审核通过，待支付");
                        map.put("upgradeLevel",upgrade.getUpgradeLevel());
                        map.put("payId",upgrade.getId());
                        map.put("payName","upgradePay");
                        map.put("payAmnt",upgrade.getAmnt());
                        map.put("payStoreId",store.getStoreId());
                        if(upgrade.getUpgradeLevel()==2) {
                            map.put("payProductName","升级为潮流馆");
                            map.put("payProductDesc","店铺由童品汇升级为潮流馆");
                        }
                        else if(upgrade.getUpgradeLevel()==3) {
                            if(store.getStoreLevel()==1){
                                map.put("payProductName","升级为品牌馆");
                                map.put("payProductDesc","店铺由童品汇升级为潮流馆");
                            }
                            else {
                                map.put("payProductName","升级为品牌馆");
                                map.put("payProductDesc","店铺由潮流馆升级为品牌馆");
                            }
                        }
                        map.put("payMode","aliPay,weChatPay");
                        rt.setData(map);
                        rt.setStatus(EnumConfig.S_CODE.OK);
                    }
                    else {
                        Map<String,Object> map = new HashMap<String,Object>();
                        map.put("storeId",store.getStoreId());
                        map.put("storeName",store.getStoreName());
                        map.put("storeAvatar",store.getStoreAvatar());
                        map.put("storeAvatarUrl",store.getStoreAvatarUrl());
                        map.put("storeImg",store.getStoreImg());
                        map.put("storeImgUrl",store.getStoreImgUrl());

                        map.put("storeLevel",store.getStoreLevel());
                        if(store.getStoreType()==1) {
                            map.put("storeLevelName", "原料商");
                        }
                        else if(store.getStoreType()==2) {
                            if (store.getStoreLevel() == 1) map.put("storeLevelName", "童品汇");
                            else if (store.getStoreLevel() == 2) map.put("storeLevelName", "潮牌馆");
                            else if (store.getStoreLevel() == 3) map.put("storeLevelName", "品牌馆");
                            else if (store.getStoreLevel() == 4) map.put("storeLevelName", "尾品汇");
                            else map.put("storeLevelName", "未知");
                        }
                        else if(store.getStoreType()==3) {
                            map.put("storeLevelName", "批发商");
                        }
                        else if(store.getStoreType()==4) {
                            map.put("storeLevelName", "经销商");
                        }
                        map.put("auditStatus",upgrade.getAuditStatus());
                        map.put("upgradeLevel",upgrade.getUpgradeLevel());
                        map.put("message","支付完成");
                        map.put("amnt",upgrade.getAmnt());//支付金额
                        rt.setData(map);
                        rt.setStatus(EnumConfig.S_CODE.OK);
                    }

                }
                else {
                    Map<String,Object> map = new HashMap<String,Object>();
                    map.put("storeId",store.getStoreId());
                    map.put("storeName",store.getStoreName());
                    map.put("storeAvatar",store.getStoreAvatar());
                    map.put("storeAvatarUrl",store.getStoreAvatarUrl());
                    map.put("storeImg",store.getStoreImg());
                    map.put("storeImgUrl",store.getStoreImgUrl());

                    map.put("storeLevel",store.getStoreLevel());
                    if(store.getStoreType()==1) {
                        map.put("storeLevelName", "原料商");
                    }
                    else if(store.getStoreType()==2) {
                        if (store.getStoreLevel() == 1) map.put("storeLevelName", "童品汇");
                        else if (store.getStoreLevel() == 2) map.put("storeLevelName", "潮牌馆");
                        else if (store.getStoreLevel() == 3) map.put("storeLevelName", "品牌馆");
                        else if (store.getStoreLevel() == 4) map.put("storeLevelName", "尾品汇");
                        else map.put("storeLevelName", "未知");
                    }
                    else if(store.getStoreType()==3) {
                        map.put("storeLevelName", "批发商");
                    }
                    else if(store.getStoreType()==4) {
                        map.put("storeLevelName", "经销商");
                    }
                    map.put("auditStatus",upgrade.getAuditStatus());
                    map.put("upgradeLevel",upgrade.getUpgradeLevel());
                    map.put("message","已失效");
                    map.put("amnt",upgrade.getAmnt());//支付金额
                    rt.setData(map);
                    rt.setStatus(EnumConfig.S_CODE.OK);
                }
            }
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public String AliNotify(AliNotifyRes aliNotify) throws Exception {
        String tradeStatus = aliNotify.getTradeStatus();
        if(tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")){//订单支付完成
            String outTradeNo = aliNotify.getOutTradeNo();
            ApiStoreUpgrade upgrade = storeUpgradeMapper.findByTradeNo(outTradeNo);
            if(upgrade != null){
                storeMapper.updateStoreLevel(upgrade.getStoreId(), upgrade.getUpgradeLevel());
                storeUpgradeMapper.updateSucessStatus(upgrade.getUpgradeId());
            }

        }
        else if(tradeStatus.equals("TRADE_CLOSED")){//订单关闭
            //String outTradeNo = aliNotify.getOut_trade_no();
            //DfcFactoryUpgrade upgrade = factoryUpgradeMapper.findByTradeNo(outTradeNo);
            //if(upgrade != null){
            //    factorySetMapper.updateFactoryType(upgrade.getFactoryId(),upgrade.getUpgradeId());
            //    factoryUpgradeMapper.updateFailStatus(upgrade.getId());
            //}
        }
        else {//其他错误
            //String outTradeNo = aliNotify.getOut_trade_no();
            //DfcFactoryUpgrade upgrade = factoryUpgradeMapper.findByTradeNo(outTradeNo);
            //if(upgrade != null){
            //    factorySetMapper.updateFactoryType(upgrade.getFactoryId(),upgrade.getUpgradeId());
            //    factoryUpgradeMapper.updateFailStatus(upgrade.getId());
            //}
        }
        return "success";
    }

    @Override
    public Result HomePage(Response<StoreInfoRes> response)  throws Exception{
        Result rt = new Result();
        try {
            Integer pageSize = 6;

            StoreInfoRes data = response.getData(StoreInfoRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiStore store = null;
            if(StringUtil.isNotEmpty(data.getStoreId())){
                store = storeMapper.get(data.getStoreId());
            }
            else {
                store = storeMapper.getByStoreId(sessionUser.getStoreId());
            }

            if(store == null){
                rt.setStatus(EnumConfig.S_CODE.STORE_NOT_EXIST);
                return rt;
            }
            Map<String,Object> map = new HashMap<String,Object>();

            map.put("storeId",store.getId());
            map.put("storeName",store.getStoreName());
            map.put("storeAvatar",store.getStoreAvatar());
            map.put("storeAvatarUrl",store.getStoreAvatarUrl());
            map.put("storeImg",store.getStoreImg());
            map.put("storeImgUrl",store.getStoreImgUrl());

            map.put("storeLevel",store.getStoreLevel());

            if(store.getStoreType()==1) {
                map.put("storeLevelName", "原料商");
            }
            else if(store.getStoreType()==2) {
                if (store.getStoreLevel() == 1) map.put("storeLevelName", "童品汇");
                else if (store.getStoreLevel() == 2) map.put("storeLevelName", "潮牌馆");
                else if (store.getStoreLevel() == 3) map.put("storeLevelName", "品牌馆");
                else if (store.getStoreLevel() == 4) map.put("storeLevelName", "尾品汇");
                else map.put("storeLevelName", "未知");
            }
            else if(store.getStoreType()==3) {
                map.put("storeLevelName", "批发商");
            }
            else if(store.getStoreType()==4) {
                map.put("storeLevelName", "经销商");
            }

            int haveFollow = followMapper.getFollowStoreByUserStoreId(user.getUserId(),store.getStoreId());

            Integer fansNum = followMapper.getFollowStoreByStoreId(store.getStoreId());

            if(haveFollow > 0)map.put("haveFollow",1);
            else map.put("haveFollow",0);
            map.put("fansNum",fansNum);

            //factoryHomeMapper.updateProductSetFactoryId();

            List<Map<String,Object>> bannerList = storeMapper.getStoreImage(store.getStoreId(), 1);//顶部轮播
            if(bannerList==null)bannerList = new ArrayList();
            map.put("banner",bannerList);

            List<Map<String,Object>> newProductList = storeMapper.getNewProduct(store.getStoreId(),0, pageSize);////新品
            map.put("newProduct",newProductList);

            List<Map<String,Object>> salesRankingList = storeMapper.getSalesRanking(store.getStoreId(), 0, pageSize);////销量排行
            map.put("salesRanking",salesRankingList);
            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(map);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }

    @Override
    public Result AllProductList(Response<StoreInfoRes> response)  throws Exception{
        Result rt = new Result();
        try {
            StoreInfoRes data = response.getData(StoreInfoRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiStore store = null;
            if(StringUtil.isNotEmpty(data.getStoreId())){
                store = storeMapper.get(data.getStoreId());
            }
            else {
                store = storeMapper.getByStoreId(sessionUser.getStoreId());
            }

            if(store == null){
                rt.setStatus(EnumConfig.S_CODE.STORE_NOT_EXIST);
                return rt;
            }
            Map<String,Object> map = new HashMap<String,Object>();

            List<Map<String,Object>> allProductList = storeMapper.AllProductList(data);////销量排行
            rt.setData(allProductList);

            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }


    @Override
    public Result NewProductBanner(Response<StoreInfoRes> response)  throws Exception{
        Result rt = new Result();
        try {
            StoreInfoRes data = response.getData(StoreInfoRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiStore store = null;
            if(StringUtil.isNotEmpty(data.getStoreId())){
                store = storeMapper.get(data.getStoreId());
            }
            else {
                store = storeMapper.getByStoreId(sessionUser.getStoreId());
            }

            if(store == null){
                rt.setStatus(EnumConfig.S_CODE.STORE_NOT_EXIST);
                return rt;
            }
            Map<String,Object> map = new HashMap<String,Object>();

            data.setStoreId(String.valueOf(store.getStoreId()));

            rt.setStatus(EnumConfig.S_CODE.OK);
            List<Map<String,Object>> bannerList = storeMapper.getStoreImage(store.getStoreId(), 2);////新品轮播
            if(bannerList==null)bannerList = new ArrayList();

            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(bannerList);
            //rt.setData(list);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }

    @Override
    public Result NewProductList(Response<StoreInfoRes> response)  throws Exception{
        Result rt = new Result();
        try {

            StoreInfoRes data = response.getData(StoreInfoRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiStore store = null;
            if(StringUtil.isNotEmpty(data.getStoreId())){
                store = storeMapper.get(data.getStoreId());
            }
            else {
                store = storeMapper.getByStoreId(sessionUser.getStoreId());
            }

            if(store == null){
                rt.setStatus(EnumConfig.S_CODE.STORE_NOT_EXIST);
                return rt;
            }
            Map<String,Object> map = new HashMap<String,Object>();

            List<Map<String,Object>> newProductList = storeMapper.getNewProduct(store.getStoreId(), data.getLimitIndex(), data.getLimitSize());////销量排行
            rt.setData(newProductList);

            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }

    @Override
    public Result ViewVideo(Response<StoreInfoRes> response)  throws Exception{
        Result rt = new Result();
        try {
            StoreInfoRes data = response.getData(StoreInfoRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiStore store = null;
            if(StringUtil.isNotEmpty(data.getStoreId())){
                store = storeMapper.get(data.getStoreId());
            }
            else {
                store = storeMapper.getByStoreId(sessionUser.getStoreId());
            }

            if(store == null){
                rt.setStatus(EnumConfig.S_CODE.STORE_NOT_EXIST);
                return rt;
            }
            List<Map<String,Object>> videoList = storeMapper.getViewVideo(store.getStoreId(), data.getLimitIndex(), data.getLimitSize());////视频点播
            rt.setData(videoList);

            //rt.setData(list);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }

    @Override
    public Result ViewLive(Response<StoreInfoRes> response)  throws Exception{
        Result rt = new Result();
        try {
            StoreInfoRes data = response.getData(StoreInfoRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }
            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            ApiStore store = null;
            if(StringUtil.isNotEmpty(data.getStoreId())){
                store = storeMapper.get(data.getStoreId());
            }
            else {
                store = storeMapper.getByStoreId(sessionUser.getStoreId());
            }

            if(store == null){
                rt.setStatus(EnumConfig.S_CODE.STORE_NOT_EXIST);
                return rt;
            }
            //视频直播
            List<Map<String,Object>> videoList = storeMapper.getLiveVideo(store.getStoreId(), data.getLimitIndex(), data.getLimitSize());////视频直播
            rt.setData(videoList);
            rt.setStatus(EnumConfig.S_CODE.OK);

        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw  ex;
        }
        return rt;
    }
}
